#include <stdlib.h>
#include "../include/soundplayer.h"

environment_t env;

environment_t new_soundplayer_environment(){ //initialize and environment
	//define defaults
	static struct _environment e;
	const char* default_device = "default";

	e.size = 0;
	e.audio_out = 0;
	e.bit_depth = 16;
	e.bit_depth_alsa = 2;
	e.audio_device = default_device;
	e.channels = 2;
	e.rate = 44100;
	e.noid3 = 0;
	e.format = 1; //default to mp3
	e.pcm_handle = NULL;
	e.progress = &sp_progress_default;
	e.message = (message_callback) &printf;
	e.filter = &sp_filter_default;
	e.overrides = 0; //no filter, format, rate, and channel autodetection

	e.status = SP_IDLE;

	return (environment_t) &e;
}

void sp_progress_default(uint32_t bytes_elapsed, uint32_t bytes_total) {
	//no progress is shown by default
	bytes_elapsed = bytes_elapsed; bytes_total = bytes_total; //remove param not used warning
	return;
}

void* sp_filter_default(char* buffer, uint32_t buffer_size) {
	//no sound post processing is preformed by default
	buffer_size = buffer_size; //remove param not used warning
	return buffer;
}

int sp_set_use_filter(int newval) {
	if (newval == 1) {
		env->overrides |= SP_OVERRIDE_FILTER;
		return 0; }
	else
		env->overrides |= !SP_OVERRIDE_FILTER;
		return -1;
}

int nstringfind(char * string, char * pattern, long num) { //handles embedded nulls
	//locate a series of characters in a string buffer
	int x = 0, y, z = 0, ret = -1;
	while(string[x] != 0 || x < num) {
		y = 0; z = 0; //reset match counter
		if(string[x] == pattern[y]) { //this must work
			while(pattern[y] != 0) {
				if(string[x+y] == pattern[y]) { z++; } //increment match counter
				y++;
			}
			if(y == z) { ret++; } //every character in pattern matched
		}
		x++;
	}
	return ret;
}

char* concat(char *s1, char *s2) {
	int	w,
		x = len(s1),
		y = len(s2);
	char *ret = malloc(x+y+1);

	for(w=0; w < x; ++w) ret[w] = s1[w];
	for(w=0; w < y; ++w) ret[w + x] = s2[w];

	ret[x+y] = '\0';
	return ret;
}

//find the length of a null terminated string
//int len(const char *string) {
	 //int ret = 0;
	 //while(string[ret] != '\0') ++ret;
	 //return ret;
//}

int len(const char *string) {
	const char *s;
	for (s = string; *s; ++s);
	return (s-string);
}

//compare strings, return 0 if they match and -1 if they don't
int cmp (const char *what, const char *where) {
	 while (*what++ == *where++) {
		if ((*what == '\0') && (*where == '\0'))
			return 0;
	 }
	 return -1;
}

int grep (char *s1, char * s2, int lim) {
	return nstringfind(s2, s1, lim);
}

int qualify_filename(char* filename) {
	//only check the last 5 characters of the file name
	int length = (len(filename) - 5);
	if(grep(".wav", &filename[length], 5)>= 0) return TYPE_WAVE;
	else if(grep(".mp3", &filename[length], 5)>= 0) return TYPE_MP3;
	else if(grep(".ogg", &filename[length], 5)>= 0) return TYPE_OGG;
	else if(grep(".aac", &filename[length], 5)>= 0) return TYPE_AAC;
	else if(grep(".flac", &filename[length], 5)>= 0) return TYPE_FLAC;
	else return -1;
}
